package com.zhenhe.api.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zhenhe.core.common.entity.RespJson;
import com.zhenhe.core.common.global.Global;
import com.zhenhe.core.common.utils.security.MD5;
import com.zhenhe.core.entity.TUserEntity;
import com.zhenhe.core.modules.service.LoginService;
import com.zhenhe.core.modules.service.TUserService;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;

@Api(value = "api/login", description = "登录接口") // Swagger annotation
@RestController
@RequestMapping("api/login")
public class APILoginController{
	private static final Logger logger = LoggerFactory.getLogger(APILoginController.class);
	
	@Resource
	private TUserService tUserService;
	
	@Resource
	private LoginService loginService;
	
	@ApiOperation(value = "api登录")
	@RequestMapping(value = "applogin", method = RequestMethod.GET)
	@ResponseBody
	public RespJson login(HttpServletRequest request, @RequestParam String userAccount, @RequestParam String password) {
		logger.info("客户端登录, userAccount : " + userAccount);
		RespJson dto = new RespJson();
		TUserEntity user = tUserService.findLoginUser(userAccount);
		if(user == null){
			dto.setResult(0);
			dto.setMsg("该用户不存在,请检查用户名是否正确");
			return dto;
		}
		String passWord = MD5.getMD5(password);
		if(user.getPassword().equals(passWord)){
			//登陆成功
			Map<String, Object> param = new HashMap<String, Object>();
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			dto.setData(param);
			dto.setResult(1);
			dto.setMsg(Global.getMessage("api.error.login.success"));
			return dto;
		}else{
			dto.setResult(0);
			dto.setMsg(Global.getMessage("api.error.login.usernameOrpasswordError"));
			return dto;
		}
	}
}
